
import Vue from "vue";
import $ from "jquery";

import {wifi,NetWorkState} from "../hos/wifi.js";
import {TcpClient, TcpDataFormat} from "../hos/tcp";

import {Activity} from "./activity.js";
import {Udp} from "../hos/udp";

class TcpTest extends Activity{

    onCreate() {
        super.onCreate();

        this.sendTimer = null;
        this.tcpClientForDevice = null;

        $(this.find("log")).append("WiFi信息:" + JSON.stringify(wifi.currentApInfo()) + "<br>");

        new Vue({
            el: this.find("connect"),
            methods: {
                click: ()=> {
                    this.connectDevice();
                }
            }});
    }


    connectDevice() {

        this.close();

        alert("连接设备");

        this.tcpClientForDevice = new TcpClient("192.168.1.3", 1234, TcpDataFormat.TEXT);
        this.tcpClientForDevice.addRecvObserver((event)=>{
            const packet = event.data;
            // 测试:收到什么回复什么
            this.tcpClientForDevice.send(packet.data, TcpDataFormat.TEXT);
        });

        this.tcpClientForDevice.addDisconnectObserver(()=>{
            this.close();
            alert("设备断开");
        });

        this.tcpClientForDevice.connect().then(()=>{
            alert("连接设备成功");
            this.sendTimer = setInterval(()=> {
                if (this.tcpClientForDevice) {
                    // alert("发送测试数据");
                    this.tcpClientForDevice.send("Hello!", TcpDataFormat.TEXT);
                }
            }, 5000);
        }, (error)=>{alert(error.errMsg);});
    }


    close() {
        if (this.tcpClientForDevice) {
            this.tcpClientForDevice.destroy();
            this.tcpClientForDevice = null;
        }

        if (this.sendTimer) {
            clearInterval(this.sendTimer);
            this.sendTimer = null;
        }
    }

    onResume() {
        super.onResume();
        // 监听网络状态变化
        wifi.addNetWorkStateObserver(this.stateObserver, this);
    }

    onPause() {
        super.onPause();

        // 移除网络状态变化监听
        wifi.removeNetWorkStateObserver(this.stateObserver);
        this.close();

    }

}

export {TcpTest};
